package vcproj2cmake;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;

public class Filter {

	private Filter mParent;
	private String mName;
	private HashSet<Filter> mChilds = new HashSet<Filter>();
	private HashSet<String> mFiles = new HashSet<String>();
	public Filter(String name, Filter parent) {
		this.mName = name;
		this.mParent = parent;
	}

	public void addChild(Filter f) {
		if (f != null)
			this.mChilds.add(f);		
	}

	public void addFile(String strFile) {
		if (strFile == null)
			return ;
		this.mFiles.add(strFile);
		
	}

	public void normalize() {
		Iterator<String> it_file = mFiles.iterator();
		HashSet<String> norm_files = new HashSet<String>();
		while(it_file.hasNext()){
			String file_str = it_file.next();
			File file = new File(file_str);
			if (file.exists())
				norm_files.add(Configuration.normalizeEscapeSeq(file_str));
		}
		this.mFiles = norm_files;		
	}

	public String writeCMakeFilter(ArrayList<String> out, File rootPath) {
		String output = "";
		if (!mFiles.isEmpty()){
			String name = mName;
			if (mParent != null)
				name = mParent.getName()+"_"+name;
			name = name.replace(" ", "_");
			output += "SET( "+name+ "\n";
			Iterator<String> iter = mFiles.iterator();
			while(iter.hasNext()){
				String file_str = iter.next();
				File file = new File(rootPath+File.separator+file_str);
				if (file.exists())
					output += Configuration.normalizeEscapeSeq(file_str)+"\n";
			}
			output+=")\n";
			String[] names = name.split("_");
			output += "SOURCE_GROUP(\"";
			for (int i = 0; i < names.length; i++)
				output+=names[i]+"\\\\";
			output +="\" FILES ${"+name+"})\n";
			out.add(name);
		}
		Iterator<Filter> iter_ch = mChilds.iterator();
		while(iter_ch.hasNext()){
			Filter child = iter_ch.next();
			output += child.writeCMakeFilter(out, rootPath);
		}
		return output;
	}

	private String getName() {
		if (mParent != null)
			return mParent.getName()+"_"+mName;
		return mName;
	}

}
